﻿// ... 其它using ...
using B.MESUI.Login.A_Public.Model;
using B.MESUI.Login.A_Public.Service;
using DevExpress.XtraEditors;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.Xpo.Helpers.AssociatedCollectionCriteriaHelper;

namespace B.MESUI.Login.A_Public
{
    public partial class EncoderForm : DevExpress.XtraEditors.XtraForm
    {
        public EncoderForm()
        {
            InitializeComponent();
            SPINEDITLENGTH.Properties.MinValue = 1;
            this.Load += EncoderForm_Load;
            SIMPLEBUTTONGENERATE.Click += SIMPLEBUTTONGENERATE_Click;
           // btnSaveRule.Click += btnSaveRule_Click;
            COMBOBOXEDITTYPE.EditValueChanged += COMBOBOXEDITTYPE_EditValueChanged;
        }

        private async void EncoderForm_Load(object sender, EventArgs e)
        {
            TEXTEDITSHOW.Anchor = AnchorStyles.Left | AnchorStyles.Right;
            await RefreshRuleComboBox();
            SPINEDITLENGTH.Properties.MinValue = 1;
            SPINEDITLENGTH.Properties.MaxValue = 9999;
            SPINEDITLENGTH.Properties.IsFloatValue = false;
            SPINEDITLENGTH.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.False;
            SPINEDITLENGTH.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
        }

        private async Task RefreshRuleComboBox()
        {
            try
            {
                var rules = await CodeGenService.GetAllRulesAsync();
                COMBOBOXEDITTYPE.Properties.Items.Clear();
                COMBOBOXEDITTYPE.Properties.Items.AddRange(rules.Select(r => r.ruleName).ToArray());
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"获取规则列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void SIMPLEBUTTONGENERATE_Click(object sender, EventArgs e)
        {
            SIMPLEBUTTONGENERATE.Enabled = false;
            try
            {
                string ruleName = COMBOBOXEDITTYPE.Text.Trim();
                if (string.IsNullOrEmpty(ruleName))
                {
                    XtraMessageBox.Show("请选择编码类型！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                bool exists = COMBOBOXEDITTYPE.Properties.Items.Contains(ruleName);
                if (!exists)
                {
                    XtraMessageBox.Show("该类型不存在，请先添加！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                string previewCode = await CodeGenService.PreviewCodeAsync(ruleName);
                TEXTEDITSHOW.Text = previewCode;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"生成编码预览失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                SIMPLEBUTTONGENERATE.Enabled = true;
            }
        }

        private async void btnSaveRule_Click(object sender, EventArgs e)
        {
            btnSaveRule.Enabled = false;
            try
            {
                string ruleName = COMBOBOXEDITTYPE.Text.Trim();
                
                string prefix = TEXTEDITPREFIX.Text.Trim();
                string connector = TEXTEDITCONNECTOR.Text.Trim();
                int serialLength = (int)SPINEDITLENGTH.Value;
                if (string.IsNullOrEmpty(ruleName) || string.IsNullOrEmpty(prefix) || serialLength <= 0)
                {
                    XtraMessageBox.Show("请输入完整规则信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 先查重
                var allRules = await CodeGenService.GetAllRulesAsync();
                if (allRules.Any(r => r.ruleName == ruleName))
                {
                    XtraMessageBox.Show("该规则名称已存在，请勿重复添加！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                bool result = await CodeGenService.CreateRuleAsync(ruleName, prefix, connector, serialLength);
                if (result)
                {
                    XtraMessageBox.Show("规则保存成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    await RefreshRuleComboBox();
                    COMBOBOXEDITTYPE.Text = ruleName;
                }
                else
                {
                    XtraMessageBox.Show("规则保存失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                btnSaveRule.Enabled = true;
            }
        }

        private async void COMBOBOXEDITTYPE_EditValueChanged(object sender, EventArgs e)
        {
            string ruleName = COMBOBOXEDITTYPE.Text.Trim();
            if (string.IsNullOrEmpty(ruleName)) return;
            bool exists = COMBOBOXEDITTYPE.Properties.Items.Contains(ruleName);
            if (!exists)
            {
                TEXTEDITPREFIX.Text = string.Empty;
                TEXTEDITCONNECTOR.Text = string.Empty;
                SPINEDITLENGTH.Value = 1;
                return;
            }
            try
            {
                var rule = await CodeGenService.GetRuleDetailAsync(ruleName);
                if (rule != null)
                {
                    TEXTEDITPREFIX.Text = rule.prefix ?? string.Empty;
                    TEXTEDITCONNECTOR.Text = rule.connector ?? string.Empty;
                    SPINEDITLENGTH.Value = rule.serialLength;
                }
                else
                {
                    TEXTEDITPREFIX.Text = string.Empty;
                    TEXTEDITCONNECTOR.Text = string.Empty;
                    SPINEDITLENGTH.Value = 1;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"获取规则详情失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void simpleButtonList1_Click(object sender, EventArgs e)
        {
            EncoderListForm encoderListForm = new EncoderListForm(COMBOBOXEDITTYPE.Text.Trim());
            encoderListForm.Show();
        }
    }
}